﻿package api;

import haxe.xml.Fast;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;

class ServerApi {
	private var url: String;
	private var authKey: String; 
	private var viewerId: Int;
	private var appName: String;
	
	public static inline var BAD_RESPONSE: String = "Не удалось установить соединение с сервером. Попробуйте перезапустить приложение.";
	
	public static function getError(fast : Fast): String {
		return fast.node.error.innerData;
	}
	
	public function new(url: String, authKey: String, viewerId: Int, appName: String) {
		this.url = url;
		this.authKey = authKey;
		this.viewerId = viewerId;
		this.appName = appName;
	}
	
	public function request(method: String, params: {}, onComplete: Xml-> Void, onError: String->Void) {
		var requestParams = new URLVariables();
		if (params != null) {
			for (field in Reflect.fields(params)) {
				// if param is null skip it
				if (Reflect.field(params, field) != null) {
					Reflect.setField(requestParams, field, Reflect.field(params, field));
				}
			}
		}
		Reflect.setField(requestParams, "app", appName);
		Reflect.setField(requestParams, "auth_key", authKey);
		Reflect.setField(requestParams, "viewer_id", Application.getViewerId());
		Reflect.setField(requestParams, "method", method);
		
		var request = new URLRequest(url);
		request.method = URLRequestMethod.POST;
		request.data = requestParams;
		//trace("Request data: " + request.data + "Request method: " + request.method);
	  
		var loader = new URLLoader();
		loader.dataFormat = URLLoaderDataFormat.TEXT;
		if (onError != null) {
			loader.addEventListener(IOErrorEvent.IO_ERROR, function(e: Dynamic) {
				onError("Connection error occured: " + e);
			});
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e: Dynamic) {
				onError("Security error occured: \n" + e );
			});
		}
	  
		if (onComplete != null) {
			loader.addEventListener(Event.COMPLETE, function(e:Event){
				var data = loader.data;
				var datastring : String = Std.string(data);
				var firstchar : Int = datastring.indexOf("<?xml");
				var overchar : Int = datastring.indexOf("><center>") + 1;
				datastring = datastring.substr(firstchar, overchar - firstchar)	;	
				data = datastring;
				onComplete(Xml.parse("" + data));
			});
		}
		try {
			loader.load(request);
		} catch (e: Dynamic) {
			if (onError != null) {
				onError("" + e);
			}
		}

	}
}